package com.tgu.home_action.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tgu.home_action.dao.*;
import com.tgu.home_action.pojo.*;
import com.tgu.home_action.pojo.exception.IMException;
import com.tgu.home_action.pojo.state.DynamicId;
import com.tgu.home_action.pojo.state.RabbitMq;
import com.tgu.home_action.pojo.state.RedisHeader;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.CaseService;
import com.tgu.home_action.service.RabbitService;
import com.tgu.home_action.service.utils.*;
import org.slf4j.Logger;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitServiceImpl implements RabbitService {
    @Autowired
    private LiveNessMapper liveNessMapper;
    @Autowired
    private VolunteerMapper volunteerMapper;
    @Autowired
    private WXService wxService;
    @Autowired
    private FamilyMapper familyMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private IMService imService;
    @Autowired
    private Logger logger;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private VolunteerCaseMapper volunteerCaseMapper;
    @Autowired
    private VolunteerInformationMapper volunteerInformationMapper;
    @Autowired
    private MessageService messageService;
    @Autowired
    private DynamicMapper dynamicMapper;
    @Autowired
    private TrackPointMapper trackPointMapper;
    @Autowired
    private RedisTemplate<String, TrackPoint> trackPointRedisTemplate;

    /**
     * 更新志愿者位置变化
     */
    @Override
    @RabbitListener(queues = "volunteer.save")
    public void setPlace(SocketMessage socketMessage) {
        try {
            System.out.println(socketMessage);
            System.out.println("volunteer.save");
            if (socketMessage == null) {
                return;
            }
            if (socketMessage.getUserId() == null || socketMessage.getLatitude() == null || socketMessage.getLongitude() == null) {
                return;
            }
            //储存位置
            Point point = new Point(socketMessage.getLongitude(), socketMessage.getLatitude());
            stringRedisTemplate.opsForGeo().add(RedisHeader.VOLUNTEER_PLACE.getHeader(), point, socketMessage.getUserId());
            stringRedisTemplate.opsForSet().add(RedisHeader.VOLUNTEER_ONLINE.getHeader(), socketMessage.getUserId());
            stringRedisTemplate.opsForSet().add(RedisHeader.VOLUNTEER_ONLINE_TWO_HOUR.getHeader(), socketMessage.getUserId());
            stringRedisTemplate.opsForValue().set(RedisHeader.VOLUNTEER_ONLINE.getHeader() + "__" + socketMessage.getUserId(), String.valueOf(new Date().getTime()));
            stringRedisTemplate.expire(RedisHeader.VOLUNTEER_ONLINE.getHeader() + "__" + socketMessage.getUserId(), 1, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set(RedisHeader.VOLUNTEER_ONLINE_TWO_HOUR.getHeader() + "__" + socketMessage.getUserId(), String.valueOf(new Date().getTime()));
            stringRedisTemplate.expire(RedisHeader.VOLUNTEER_ONLINE_TWO_HOUR.getHeader() + "__" + socketMessage.getUserId(), 2, TimeUnit.HOURS);
            //发送志愿者位置变化
            List<Integer> caseIds = volunteerCaseMapper.getIngCaseIdByVolunteerId(Integer.valueOf(socketMessage.getUserId()));
            for (Integer caseId :
                    caseIds) {
                Map<String, Object> data = socketMessage.getData();
                if(socketMessage.getIsSave()!=null&&socketMessage.getIsSave()==1){
                    //先储存轨迹
                    trackPointRedisTemplate.opsForList().rightPush(RedisHeader.TRACK.getHeader()+caseId+socketMessage.getUserId(),new TrackPoint(socketMessage.getLongitude(),socketMessage.getLatitude(),caseId,Integer.valueOf(socketMessage.getUserId()),new Timestamp(new Date().getTime())));
                    //查询已存redis轨迹
                    List<TrackPoint> trackPoints=trackPointRedisTemplate.opsForList().range(RedisHeader.TRACK.getHeader()+caseId+socketMessage.getUserId(), 0,-1);
                    if(trackPoints==null){
                        trackPoints=new ArrayList<>();
                    }
                    //查询已存数据库轨迹
                    List<TrackPoint> trackPointList=trackPointMapper.getTrackPoint(Integer.valueOf(socketMessage.getUserId()),caseId);
                    List<TrackPoint> points=new ArrayList<>();
                    for(TrackPoint trackPoint:trackPointList){
                        List<TrackPoint> trackNode=JSON.parseArray(trackPoint.getPoint(),TrackPoint.class);
                        if(trackNode!=null){
                            points.addAll(trackNode);
                        }
                    }
                    points.addAll(trackPoints);
                    data.put("track",points);
                    System.out.println(points);
                    //如果满100个就存到数据库
                    if(trackPoints.size()>=2){
                        points= DouglasPeuckerUtils.dp(points);
                        System.out.println(points);
                        UpdateWrapper<TrackPoint> trackPointUpdateWrapper=new UpdateWrapper<>();
                        trackPointUpdateWrapper.eq("volunteer_id",Integer.valueOf(socketMessage.getUserId()));
                        trackPointUpdateWrapper.eq("case_id",caseId);
                        trackPointMapper.delete(trackPointUpdateWrapper);
                        for(int i=0;(5000*i)<=points.size();i++){
                            System.out.println((points.size()-5000*i)>0);
                            int ofIndex=(points.size()-5000*(i+1)>0)?5000*i:points.size();
                            System.out.println(ofIndex);
                            trackPointMapper.insert(new TrackPoint(JSON.toJSONString(points.subList(5000*i,ofIndex)),caseId,Integer.valueOf(socketMessage.getUserId())));
                        }
                        trackPointRedisTemplate.delete(RedisHeader.TRACK.getHeader()+caseId+socketMessage.getUserId());
                    }
                }
                ResponseData<Map<String, Object>> responseData = new ResponseData<>(ResponseState.VOLUNTEER_PLACE_UPDATE.getMessage(), ResponseState.VOLUNTEER_PLACE_UPDATE.getValue(), data);
                simpMessagingTemplate.convertAndSend("/case/" + caseId, responseData);
            }
            //添加活跃度
            try {
                String dateStr = StringService.dateToString(new Date(), "yyyy-MM-dd");
                Date date = StringService.stingToDate(dateStr, "yyyy-MM-dd");
                Timestamp timestamp = new Timestamp(date.getTime());
                LiveNess liveNess = liveNessMapper.getByVolunteerIdAndDate(new LiveNess(Integer.valueOf(socketMessage.getUserId()), timestamp));
                if (liveNess == null) {
                    liveNessMapper.insertLiveNess(new LiveNess(Integer.valueOf(socketMessage.getUserId()), timestamp));
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 推送新的案件/发送微信通知
     */
    @RabbitListener(queues = "case.send")
    public void sendCase(Case nowCase) {
        simpMessagingTemplate.convertAndSend( "/case", nowCase);
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending();
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().radius(RedisHeader.VOLUNTEER_PLACE.getHeader(), new Circle(new Point(nowCase.getLongitude(), nowCase.getLatitude()), new Distance(5, Metrics.KILOMETERS)), geoRadiusCommandArgs);
        Integer[] volunteerIds;
        //有位置且满足条件的
        List<Integer> onlineIds = new ArrayList<>();
        //如果5公里内没人则扩大到10公里
        if (geoResults == null || geoResults.getContent().size() == 0) {
            geoResults = stringRedisTemplate.opsForGeo().radius(RedisHeader.VOLUNTEER_PLACE.getHeader(), new Circle(new Point(nowCase.getLongitude(), nowCase.getLatitude()), new Distance(10, Metrics.KILOMETERS)), geoRadiusCommandArgs);
            if (geoResults != null && geoResults.getContent().size() != 0) {
                for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
                    System.out.println(geoResult);
                    RedisGeoCommands.GeoLocation<String> geoLocation = geoResult.getContent();
                    Integer id = Integer.valueOf(geoLocation.getName());
                    onlineIds.add(id);
                    Boolean isExist = stringRedisTemplate.opsForSet().isMember(RedisHeader.VOLUNTEER_ONLINE.getHeader(), String.valueOf(id));
                    if (isExist == null) {
                        isExist = false;
                    }
                    if (isExist) {
                        nowCase.setDistance(geoResult.getDistance().getValue());
                        ResponseData<Case> responseData = new ResponseData<>(ResponseState.NEW_CASE.getMessage(), ResponseState.NEW_CASE.getValue(), nowCase);
                        simpMessagingTemplate.convertAndSendToUser("volunteer_"+String.valueOf(id), "/volunteer", responseData);
                    }
                }
            }
        } else {
            for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
                RedisGeoCommands.GeoLocation<String> geoLocation = geoResult.getContent();
                Integer id = Integer.valueOf(geoLocation.getName());
                onlineIds.add(id);
                //判断志愿者是否在线
                Boolean isExist = stringRedisTemplate.opsForSet().isMember(RedisHeader.VOLUNTEER_ONLINE.getHeader(), String.valueOf(id));
                if (isExist == null) {
                    isExist = false;
                }
                if (isExist) {
                    nowCase.setDistance(geoResult.getDistance().getValue());
                    ResponseData<Case> responseData = new ResponseData<>(ResponseState.NEW_CASE.getMessage(), ResponseState.NEW_CASE.getValue(), nowCase);
                    simpMessagingTemplate.convertAndSendToUser(String.valueOf(id), "/volunteer", responseData);
                }
            }
        }
        volunteerIds = volunteerInformationMapper.getVolunteerIdByPlaceNotOnline(onlineIds, nowCase);
        for (Integer volunteerId :
                onlineIds) {
            sendCaseStartWxMessage(volunteerId, nowCase);
        }
        for (Integer volunteerId :
                volunteerIds) {
            sendCaseStartWxMessage(volunteerId, nowCase);
        }
    }

    /**
     * 储存动态/新案件短信通知
     */
    @RabbitListener(queues = "case.send.message")
    public void sendCaseMessage(Case nowCase) {

        try {
            Family family = familyMapper.getById(nowCase.getFamilyId());
            Dynamic dynamic = new Dynamic(nowCase.getId(), nowCase.getFamilyId(), null, DynamicId.START_CASE.getValue(), family.getName(), family.getAvatarUrl());
            dynamicMapper.insertDynamic(dynamic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending();
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().radius(RedisHeader.VOLUNTEER_PLACE.getHeader(), new Circle(new Point(nowCase.getLongitude(), nowCase.getLatitude()), new Distance(5, Metrics.KILOMETERS)), geoRadiusCommandArgs);
        Integer[] volunteerIds;
        List<Integer> onlineIds = new ArrayList<>();
        //如果5公里内没人则扩大到10公里
        if (geoResults == null || geoResults.getContent().size() == 0) {
            geoResults = stringRedisTemplate.opsForGeo().radius(RedisHeader.VOLUNTEER_PLACE.getHeader(), new Circle(new Point(nowCase.getLongitude(), nowCase.getLatitude()), new Distance(10, Metrics.KILOMETERS)), geoRadiusCommandArgs);
            if (geoResults != null && geoResults.getContent().size() != 0) {
                for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
                    System.out.println(geoResult);
                    RedisGeoCommands.GeoLocation<String> geoLocation = geoResult.getContent();
                    Integer id = Integer.valueOf(geoLocation.getName());
                    onlineIds.add(id);
                }
            }
        } else {
            for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : geoResults.getContent()) {
                RedisGeoCommands.GeoLocation<String> geoLocation = geoResult.getContent();
                Integer id = Integer.valueOf(geoLocation.getName());
                onlineIds.add(id);
            }
        }
        volunteerIds = volunteerInformationMapper.getVolunteerIdByPlaceNotOnline(onlineIds, nowCase);
        for (Integer volunteerId :
                onlineIds) {
            String phone = volunteerMapper.getPhoneById(volunteerId);
            try {
                messageService.sendMessage(phone, "850017", null);
            } catch (TencentCloudSDKException e) {
                e.printStackTrace();
                logger.error("Id为{}的志愿者短信通知失败", volunteerId);
            }
        }
        for (Integer volunteerId :
                volunteerIds) {
            String phone = volunteerMapper.getPhoneById(volunteerId);
            try {
                messageService.sendMessage(phone, "850017", null);
            } catch (TencentCloudSDKException e) {
                logger.error("Id为{}的志愿者短信通知失败", volunteerId);
                e.printStackTrace();
            }
        }
    }

    /**
     * 案件开始的微信通知
     */
    private void sendCaseStartWxMessage(Integer volunteerId, Case nowCase) {
        String accessToken = stringRedisTemplate.opsForValue().get(RedisHeader.WX_VOLUNTEER_ACCESS_TOKEN.getHeader());
        if (accessToken == null) {
            Map<String, Object> data = wxService.getVolunteerAccessToken();
            accessToken = (String) data.get("access_token");
            int expiresIn = (int) data.get("expires_in");
            stringRedisTemplate.opsForValue().set(RedisHeader.WX_VOLUNTEER_ACCESS_TOKEN.getHeader(), accessToken, expiresIn, TimeUnit.SECONDS);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("thing5", getMessageMap(nowCase.getCity() + nowCase.getDistrict() + nowCase.getPlace()));
        data.put("time7", getMessageMap(StringService.dateToString(nowCase.getStartTime(), "yyyy-MM-dd HH:mm:ss")));
        data.put("time8", getMessageMap(StringService.dateToString(new Date(nowCase.getStartTime().getTime() + 3 * 24 * 3600 * 1000), "yyyy-MM-dd HH:mm:ss")));
        data.put("thing10", getMessageMap("请进入小程序确认或拒绝该任务"));
        String openid = volunteerMapper.getOpenidById(volunteerId);
        Map<String, Object> result = null;
        try {
            result = wxService.sendMessage(accessToken, openid, "I4wZW_PzQCgZh_e7fTih63JKYuIpt-japiy8LWSmH8Y", "pages/myMissions/index", data);
        } catch (Exception e) {
            logger.error("Id为{}的志愿者微信通知失败", volunteerId);
            e.printStackTrace();
        }
        System.out.println(result);
    }

    /**
     * 发送微信消息的参数格式
     */
    private Map<String, Object> getMessageMap(Object value) {
        Map<String, Object> data = new HashMap<>();
        data.put("value", value);
        return data;
    }

    /**
     * 案件信息变化
     */
    @RabbitListener(queues = "case.information.update")
    public void caseInformationUpdate(Case nowCase) {
        ResponseData<Case> responseData = new ResponseData<>(ResponseState.CASE_INFORMATION.getMessage(), ResponseState.CASE_INFORMATION.getValue(), nowCase);
        simpMessagingTemplate.convertAndSend("/case/" + nowCase.getId(), responseData);
    }

    /**
     * 创建案件群组
     */
    @RabbitListener(queues = "case.create.group")
    public void createGroup(Case newCase) {
        try {
            String groupId = imService.createGroup("case_" + newCase.getId(), null);
            stringRedisTemplate.opsForValue().set(RedisHeader.GROUP_ID.getHeader() + newCase.getId(), groupId);
            //将家属加入群组
            Boolean isExist = imService.accountCheck("family_" + newCase.getFamilyId());
            if (!isExist) {
                imService.insertUser("family_" + newCase.getFamilyId(), familyMapper.getNameById(newCase.getFamilyId()), null);
                imService.setMessage("family_" + newCase.getFamilyId(), "family", newCase.getFamilyId());
            }
            imService.addMember(groupId, "family_" + newCase.getFamilyId());
            //发送系统通知
            imService.sendGroupMsg(groupId, "任务已开始");
        } catch (IMException e) {
            e.printStackTrace();
        }
    }

    /**
     * 志愿者加入案件
     */
    @RabbitListener(queues = "volunteer.in")
    public void volunteerInCase(VolunteerCase volunteerCase) {
        //记录动态
        try {
            Volunteer volunteer = volunteerMapper.getById(volunteerCase.getVolunteerId());
            VolunteerInformation volunteerInformation = volunteerInformationMapper.getInformationByVolunteerId(volunteerCase.getVolunteerId());
            dynamicMapper.insertDynamic(new Dynamic(volunteerCase.getCaseId(), null, volunteerCase.getVolunteerId(), DynamicId.VOLUNTEER_IN.getValue(), volunteerInformation.getName(), volunteer.getAvatarUrl()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发送通知
        ResponseData<Integer> responseData = new ResponseData<>(ResponseState.VOLUNTEER_IN.getMessage(), ResponseState.VOLUNTEER_IN.getValue(), volunteerCase.getVolunteerId());
        simpMessagingTemplate.convertAndSend("/case/" + volunteerCase.getCaseId(), responseData);
        //加入群组
        String groupId = stringRedisTemplate.opsForValue().get(RedisHeader.GROUP_ID.getHeader() + volunteerCase.getCaseId());
        if (groupId == null) {
            logger.error("该案件不存在群组");
            return;
        }
        Boolean isExist = null;
        try {
            isExist = imService.accountCheck("volunteer_" + volunteerCase.getVolunteerId());
            String name = volunteerInformationMapper.getNameByVolunteerId(volunteerCase.getVolunteerId());
            if (!isExist) {
                imService.insertUser("volunteer_" + volunteerCase.getVolunteerId(), name, null);
                imService.setMessage("volunteer_" + volunteerCase.getVolunteerId(), "volunteer", volunteerCase.getVolunteerId());
            }
            imService.addMember(groupId, "volunteer_" + volunteerCase.getVolunteerId());
            //发送系统通知
            imService.sendGroupMsg(groupId, "志愿者" + name + "加入案件");
        } catch (IMException e) {
            e.printStackTrace();
        }

    }

    /**
     * 志愿者退出案件
     */
    @RabbitListener(queues = "volunteer.out")
    public void volunteerOutCase(VolunteerCase volunteerCase) {
        try {
            Volunteer volunteer = volunteerMapper.getById(volunteerCase.getVolunteerId());
            VolunteerInformation volunteerInformation = volunteerInformationMapper.getInformationByVolunteerId(volunteerCase.getVolunteerId());
            dynamicMapper.insertDynamic(new Dynamic(volunteerCase.getCaseId(), null, volunteerCase.getVolunteerId(), DynamicId.VOLUNTEER_OUT.getValue(), volunteerInformation.getName(), volunteer.getAvatarUrl()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        ResponseData<Integer> responseData = new ResponseData<>(ResponseState.VOLUNTEER_OUT.getMessage(), ResponseState.VOLUNTEER_OUT.getValue(), volunteerCase.getVolunteerId());
        simpMessagingTemplate.convertAndSend("/case/" + volunteerCase.getCaseId(), responseData);
        String groupId = stringRedisTemplate.opsForValue().get(RedisHeader.GROUP_ID.getHeader() + volunteerCase.getCaseId());
        if (groupId == null) {
            logger.error("该案件不存在群组");
            return;
        }
        try {
            imService.deleteMember(groupId, "volunteer_" + volunteerCase.getVolunteerId());
            String name = volunteerInformationMapper.getNameByVolunteerId(volunteerCase.getVolunteerId());
            imService.sendGroupMsg(groupId, "志愿者" + name + "退出案件");
        } catch (IMException e) {
            e.printStackTrace();
        }
    }

    /**
     * 人脸识别结果超过80%
     */
    @RabbitListener(queues = "face.success")
    public void faceSuccess(Face face) {
        ResponseData<Face> responseData = new ResponseData<>(ResponseState.FACE_OVER_EIGHTY.getMessage(), ResponseState.FACE_OVER_EIGHTY.getValue(), face);
        OldMan oldMan = face.getOldMan();
        //判断该老人当前是否有案件
        String phone = null;
        if (oldMan != null) {
            List<Case> cases = oldMan.getCases();
            for (Case nowCase : cases) {
                if (nowCase.getState() == 1 || nowCase.getState() == 3) {
                    try {
                        Volunteer volunteer = volunteerMapper.getById(face.getVolunteerId());
                        VolunteerInformation volunteerInformation = volunteerInformationMapper.getInformationByVolunteerId(face.getVolunteerId());
                        dynamicMapper.insertDynamic(new Dynamic(nowCase.getId(), null, face.getVolunteerId(), DynamicId.FACE_SUCCESS.getValue(), volunteerInformation.getName(), volunteer.getAvatarUrl()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    simpMessagingTemplate.convertAndSend("/case/" + nowCase.getState(), responseData);
                    phone = oldMan.getPhone();
                    String groupId = stringRedisTemplate.opsForValue().get(RedisHeader.GROUP_ID.getHeader() + nowCase.getId());
                    if (groupId == null) {
                        logger.error("该案件不存在群组");
                        return;
                    }
                    try {
                        String name = volunteerInformationMapper.getNameByVolunteerId(face.getVolunteerId());
                        imService.sendGroupMsg(groupId, "志愿者" + name + "成功匹配了人脸信息");
                    } catch (IMException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
            if (phone == null) {
                phone = familyMapper.getPhoneByOldManId(oldMan.getId());
            }
        }
        try {
            messageService.sendMessage(phone, "870931", null);
        } catch (TencentCloudSDKException e) {
            logger.error("老人Id为{}人脸识别确认短信发送失败", face.getOldManId());
            e.printStackTrace();
        }

    }

//    /**
//     * 结束案件
//     */
//    @RabbitListener(queues = "case.end")
//    public void endCase(Case nowCase){
//        System.out.println("结束案件");
//        System.out.println(nowCase);
//        ResponseData<Object> responseData = null;
//        if(nowCase.getState()==2){
//            responseData=new ResponseData<>(ResponseState.CASE_FINISH.getMessage(), ResponseState.CASE_FINISH.getValue());
//        }else if(nowCase.getState()==4){
//            responseData=new ResponseData<>(ResponseState.CASE_CANCEL.getMessage(), ResponseState.CASE_CANCEL.getValue());
//        }else {
//            return;
//        }
//        simpMessagingTemplate.convertAndSend("/case/"+nowCase.getId(),responseData);
//        String groupId=stringRedisTemplate.opsForValue().get(RedisHeader.GROUP_ID.getHeader()+nowCase.getId());
//        try {
//            if(nowCase.getState()==2){
//                imService.sendGroupMsg(groupId,"案件已完成，1小时后将解散该群组");
//            }else if(nowCase.getState()==4){
//                imService.sendGroupMsg(groupId,"案件已取消，1小时后将解散该群组");
//            }else {
//                return;
//            }
//            try {
//                TimeUnit.HOURS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            imService.destroyGroup(groupId);
//            stringRedisTemplate.delete(RedisHeader.GROUP_ID.getHeader()+nowCase.getId());
//        } catch (IMException e) {
//            e.printStackTrace();
//        }
//    }

    @RabbitListener(queues = "case.finish")
    public void finishCase(Case nowCase) {
        System.out.println("完成案件");
        System.out.println(nowCase);
        ResponseData<Object> responseData = null;
        if (nowCase.getState() == 2) {
            try {
                Family family = familyMapper.getById(nowCase.getFamilyId());
                Dynamic dynamic = new Dynamic(nowCase.getId(), nowCase.getFamilyId(), null, DynamicId.FINISH_CASE.getValue(), family.getName(), family.getAvatarUrl());
                dynamicMapper.insertDynamic(dynamic);
            } catch (Exception e) {
                e.printStackTrace();
            }

            responseData = new ResponseData<>(ResponseState.CASE_FINISH.getMessage(), ResponseState.CASE_FINISH.getValue());
        } else if (nowCase.getState() == 4) {
            try {
                Family family = familyMapper.getById(nowCase.getFamilyId());
                Dynamic dynamic = new Dynamic(nowCase.getId(), nowCase.getFamilyId(), null, DynamicId.CANCEL_CASE.getValue(), family.getName(), family.getAvatarUrl());
                dynamicMapper.insertDynamic(dynamic);
            } catch (Exception e) {
                e.printStackTrace();
            }
            responseData = new ResponseData<>(ResponseState.CASE_CANCEL.getMessage(), ResponseState.CASE_CANCEL.getValue());
        } else {
            return;
        }
        simpMessagingTemplate.convertAndSend("/case/" + nowCase.getId(), responseData);
        String groupId = stringRedisTemplate.opsForValue().get(RedisHeader.GROUP_ID.getHeader() + nowCase.getId());
        try {
            if (nowCase.getState() == 2) {
                imService.sendGroupMsg(groupId, "案件已完成，1小时后将解散该群组");
            } else if (nowCase.getState() == 4) {
                imService.sendGroupMsg(groupId, "案件已取消，1小时后将解散该群组");
            } else {
                return;
            }
//            try {
//                TimeUnit.HOURS.sleep(1);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            imService.destroyGroup(groupId);
//            stringRedisTemplate.delete(RedisHeader.GROUP_ID.getHeader() + nowCase.getId());
        } catch (IMException e) {
            e.printStackTrace();
        }
    }

}
